package com.ilop.sthome.utils.system;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;

import com.alibaba.sdk.android.openaccount.ConfigManager;
import com.alibaba.sdk.android.openaccount.config.LanguageCode;
import com.aliyun.iot.aep.oa.OALanguageHelper;
import com.aliyun.iot.aep.sdk.IoTSmart;
import com.ilop.sthome.common.CommonId;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.TimeZone;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.POWER_SERVICE;

/**
 * @author skygge
 * @Date on 2020-02-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：系统工具
 */
public class AppUtil {

    private static final String TAG = AppUtil.class.getSimpleName();
    private Context context;

    public AppUtil(Context context){
        this.context = context;
    }

    public static Context attachBaseContext(Context newBase) {
        setLanguage(newBase);
        return newBase;
    }

    public static void setLanguage(@SuppressWarnings("unused") Context context) {
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        Log.i(TAG, "setLanguage: " + language);

        if (language.equals("zh")) {
            ConfigManager.getInstance().setLanguageCode(LanguageCode.CHINESE);
        } else {
            ConfigManager.getInstance().setLanguageCode(LanguageCode.ENGLISH);
        }
        if ("zh".equalsIgnoreCase(language)) {
            OALanguageHelper.setLanguageCode(Locale.SIMPLIFIED_CHINESE);
            IoTSmart.setLanguage("zh-CN");
        } else if ("en".equalsIgnoreCase(language)) {
            OALanguageHelper.setLanguageCode(Locale.US);
            IoTSmart.setLanguage("en-US");
        } else if ("fr".equalsIgnoreCase(language)) {
            OALanguageHelper.setLanguageCode(Locale.FRANCE);
            IoTSmart.setLanguage("fr-FR");
        } else if ("de".equalsIgnoreCase(language)) {
            OALanguageHelper.setLanguageCode(Locale.GERMANY);
            IoTSmart.setLanguage("de-DE");
        } else if ("es".equalsIgnoreCase(language)) {
            OALanguageHelper.setLanguageCode(new Locale("es", "ES"));
            IoTSmart.setLanguage("es-ES");
        } else {
            OALanguageHelper.setLanguageCode(Locale.US);
            IoTSmart.setLanguage("en-US");
        }
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的VersionName
     */
    public static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的VersionCode
     */
    public static synchronized long getVersionCode(Context context) {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
        }
        return appVersionCode;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的PackageName
     */
    public static synchronized String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断当前应用是否是debug状态
     */
    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取APP版本号
     * @return response
     */
    public static String getResultForHttpGet(){
        OkHttpClient client=new OkHttpClient();
        Request request = new Request.Builder().url(CommonId.APP_VERSION_LINK) .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 国际化开发中的时区问题之——夏令时，冬令时
     * @return timeZone
     */
    public static int getTimeZone() {
        //  这里注释的是之前获取到的时区，但是不分夏令时和冬令时（格林威治时间划分的）
        //  int _t = TimeZone.getDefault().getRawOffset() / (3600 * 1000);
        //  改为如下，获取系统的时间并且计算出时区就可以了
        return TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (3600 * 1000);
    }

    /**
     * 读取系统语言
     * @return language
     */
    public String readLanguage() {
        Resources resources = context.getResources();
        Locale locale = resources.getConfiguration().locale;//获得local对象
        return locale.getLanguage();
    }

    /**
     * 获取系统经纬度和定位
     */
    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        assert locationManager != null;
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

    /**
     * 获取便捷式热点状态
     */
    public static boolean isWifiApOpen(Context context) {
        try {
            WifiManager manager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            //通过放射获取 getWifiApState()方法
            Method method = manager.getClass().getDeclaredMethod("getWifiApState");
            //调用getWifiApState() ，获取返回值
            int state = (int) method.invoke(manager);
            //通过放射获取 WIFI_AP的开启状态属性
            Field field = manager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
            //获取属性值
            int value = (int) field.get(manager);
            //判断是否开启
            if (state == value) {
                return true;
            } else {
                return false;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 屏幕亮屏
     */
    public static void screenOn(Context context) {
        // turn on screen
        PowerManager mPowerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
        mWakeLock.acquire(10*60*1000L /*10 minutes*/);
        mWakeLock.release();
    }
}
